import java.util.Arrays;

class Solution {
    public static void main(String[] args) {
        int[][] martrix1 = new int[][] {{1,2,3},{4,5,6},{7,8,9}};
        int[][] martrix2 = new int[][] {{7},{9},{6}};
        spiralOrder(martrix1);
    }
    public static int[] spiralOrder(int[][] matrix) {
        //i行j列
        int i = 0,j = 0;
        boolean high = false,down = false,left = false,right = false;
        //列长,行长
        int collen = matrix[0].length,rowlen = matrix.length;
        int[] arr = new int[collen*rowlen];
        //记录减几行
        int res = 0;
        //记录arr下标
        int ret = 0;
        //先走第一行
        while(j<collen-res) {
            arr[ret++] = matrix[i][j++];
        }
        j--;
        while(ret < arr.length) {
            if(collen-1 == j) {
                right = true;
            }
            if(0 == j) {
                left = true;
            }
            if(0 == i) {
                high = true;
            }
            if(rowlen - 1 == i) {
                down = true;
            }

            if(right && ret < arr.length) {
                while(i<rowlen-res-1) {
                    arr[ret++] = matrix[++i][j];
                }
                right = false;
                down = true;
            }
            if(down && ret < arr.length) {
                while(j>=res+1) {
                    arr[ret++] = matrix[i][--j];
                }
                down = false;
                left = true;
                res++;
            }
            if(left && ret < arr.length) {
                while(i>=res+1) {
                    arr[ret++] = matrix[--i][j];
                }
                left = false;
                high = true;
            }
            if(high && ret < arr.length) {
                while(j<collen-res-1) {
                    arr[ret++] = matrix[i][++j];
                }
                right = true;
                high = false;
            }
        }
        return arr;
    }
}